package com.gitee.huanminabc.utils_common.requestclient.okhttp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gitee.huanminabc.jcommon.exception.CommonException;
import com.gitee.huanminabc.jcommon.file.IoStreamUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Proxy;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

/**
 * @Author 胡安民 ,自研改造
 */
@Slf4j
public class OkHttpUtil {
    private final static int LIMIT_MAXIMUM_POOL_SIZE = 1000;
    private static final Map<String, OkHttpClient> okHttpClientMap = new ConcurrentHashMap<>();
    public static final String DEFAULT_THREAD_FACTORY_NAME = "$$$--DEFAULT_OKHTTP_UTILS--$$$";

    private static OkHttpClient okHttpClient = null;

    static {
        okHttpClientMap.put(DEFAULT_THREAD_FACTORY_NAME, createOkHttpClient(LIMIT_MAXIMUM_POOL_SIZE));
    }

    private Map<String, String> headerMap;
    private Map<String, Object> paramMap;
    private String url;
    private Request.Builder request;

    //懒汉模式,单例
    private OkHttpUtil() {
        okHttpClient = okHttpClientMap.get(DEFAULT_THREAD_FACTORY_NAME);
    }

    private OkHttpUtil(String httpName) {
        okHttpClient = okHttpClientMap.computeIfAbsent(httpName, k -> createOkHttpClient(100));
    }

    /**
     * 初始化okHttpClient，并且允许https访问
     */
    private static OkHttpClient createOkHttpClient(int maxIdleConnections) {

        TrustManager[] trustManagers = buildTrustManagers();
//        addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");

        return new OkHttpClient.Builder()
                //设置连接超时时间 默认是10s
                .connectTimeout(10, TimeUnit.SECONDS)
                //写入超时时间 默认是10s (一般不调整)
                .writeTimeout(10, TimeUnit.SECONDS)
                //读取超时时间 默认是10s (一般不调整)
                .readTimeout(10, TimeUnit.SECONDS)
                //跳过ssl认证(https)
                .sslSocketFactory(createSSLSocketFactory(trustManagers), (X509TrustManager) trustManagers[0])
                .hostnameVerifier((hostName, session) -> true)
                .retryOnConnectionFailure(true)
                // 最大连接数量  , 持续存活的连接时间
                .connectionPool(new ConnectionPool(maxIdleConnections, 10, TimeUnit.MINUTES))
                .build();
    }

    /**
     * 创建OkHttpUtil
     */
    public static OkHttpUtil builder() {
        return new OkHttpUtil();
    }
    public static OkHttpUtil builder(String httpName) {
        return new OkHttpUtil(httpName);
    }


    //设置连接超时时间(建议比系统最大超时时间低一些,比如rpc设置的15s断开,那么这里设置14s)
    public OkHttpUtil connectTimeout(long time, TimeUnit timeUnit) {
        okHttpClient = okHttpClient.newBuilder().connectTimeout(time, timeUnit).build();
        return this;
    }

    //设置写入超时时间(一般不调整)
    public OkHttpUtil writeTimeout(long time, TimeUnit timeUnit) {
        okHttpClient = okHttpClient.newBuilder().writeTimeout(time, timeUnit).build();
        return this;
    }

    //设置读取超时时间(一般不调整)
    public OkHttpUtil readTimeout(long time, TimeUnit timeUnit) {
        okHttpClient = okHttpClient.newBuilder().readTimeout(time, timeUnit).build();
        return this;
    }

    //设置代理
    //设置代理方式
    //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080));
    public OkHttpUtil proxy(Proxy proxy) {
        okHttpClient = okHttpClient.newBuilder().proxy(proxy).build();
        return this;
    }

    //自定义线程池
    //new ConnectionPool(500, 10, TimeUnit.MINUTES)
    public OkHttpUtil connectionPool(ConnectionPool connectionPool) {
        okHttpClient = okHttpClient.newBuilder().connectionPool(connectionPool).build();
        return this;
    }


    /**
     * 添加url
     *
     * @param url 请求地址
     */
    public OkHttpUtil url(String url) {
        this.url = url;
        return this;
    }

    /**
     * 添加参数
     * 注意: 如果是POST请求并且key中存在JsonBody,那么就只会使用JsonBody的值作为参数其他参数会被忽略
     *
     * @param key   参数名
     * @param value 参数值
     */
    public OkHttpUtil addParam(String key, Object value) {
        if (paramMap == null) {
            paramMap = new LinkedHashMap<>(16);
        }
        paramMap.put(key, value);
        return this;
    }

    /**
     * 添加请求头
     *
     * @param key   参数名
     * @param value 参数值
     */
    public OkHttpUtil addHeader(String key, String value) {
        if (headerMap == null) {
            headerMap = new LinkedHashMap<>(16);
        }
        headerMap.put(key, value);
        return this;
    }

    /**
     * 初始化get方法
     */
    public OkHttpUtil get() {
        request = new Request.Builder().get();
        StringBuilder urlBuilder = new StringBuilder(url);
        if (paramMap != null) {
            urlBuilder.append("?");
            try {
                for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                    urlBuilder.append(URLEncoder.encode(entry.getKey(), "utf-8")).
                            append("=").
                            append(URLEncoder.encode((String) entry.getValue(), "utf-8")).
                            append("&");
                }
            } catch (Exception e) {
                throw new CommonException(e);
            }
            urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        }
        request.url(urlBuilder.toString());
        return this;
    }

    /**
     * 初始化post方法
     *
     * @param type json/form/file 三种类型 json:转为json字符串 form:普通表单提交 file:文件上传+表单提交
     *             file类型时，需要添加文件参数，key为filePath ，value为文件路径, 或者value为文件字节(如果是文件字节，需要添加文件名参数，key为fileName，value为文件名
     *             file类型时，需要添加文件参数，key为filePaths ，value为文件路径,多个路径使用字符串数组, value为文件字节,多个文件字节使用二维byte数组(如果是文件字节，需要添加文件名参数，key为fileNames，value为文件名,多个文件名使用数组方式)
     */
    public OkHttpUtil post(String type) {
        RequestBody requestBody = null;
        switch (type) {
            case "json":
                String json = "";
                if (paramMap != null) {
                    Object object = paramMap.get("JsonBody"); //如果有JsonBody参数，那么就直接使用JsonBody参数
                    if (object != null) {
                        json = JSONObject.toJSONString(object);
                    } else {
                        json = JSONObject.toJSONString(paramMap);
                    }
                }
                requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),json);
                break;
            case "form":
                FormBody.Builder formBody = new FormBody.Builder();
                if (paramMap != null) {
                    for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                        String key = entry.getKey();
                        Object value = entry.getValue();
                        formBody.add(key, String.valueOf(value));
                    }
                }
                requestBody = formBody.build();
                break;
            case "file":
                String fileKey = "file";
                MultipartBody.Builder builder = new MultipartBody.Builder();
                builder.setType(MultipartBody.FORM);
                for (Map.Entry<String, Object> field : paramMap.entrySet()) { // 添加表单信息
                    if ("fileKey".equals(field.getKey())) {
                        fileKey = (String) field.getValue();
                    }
                    //排除文件参数
                    if ("filePath".equals(field.getKey()) || "filePaths".equals(field.getKey()) ||
                            "fileByte".equals(field.getKey()) || "fileByteName".equals(field.getKey()) ||
                            "fileBytes".equals(field.getKey()) || "fileBytesNames".equals(field.getKey()) ||
                            "fileKey".equals(field.getKey()
                            )) {
                        continue;
                    }
                    builder.addFormDataPart(field.getKey(), (String) field.getValue());
                }
                //单文件上传
                String filePath = (String) paramMap.get("filePath");
                if (filePath != null) {
                    File file = new File(filePath);
                    builder.addFormDataPart(fileKey, file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"),file));
                }
                //多文件上传
                String[] filePaths = (String[]) paramMap.get("filePaths");
                if (filePaths != null) {
                    for (String filePath1 : filePaths) {
                        File file = new File(filePath1);
                        builder.addFormDataPart(fileKey, file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"),file));
                    }
                }
                //上传字节流
                byte[] fileByte = (byte[]) paramMap.get("fileByte");
                String fileByteName = (String) paramMap.get("fileByteName");//字节流文件名
                if (fileByte != null) {
                    builder.addFormDataPart(fileKey, fileByteName, RequestBody.create(MediaType.parse("application/octet-stream"),fileByte));
                }
                //上传字节流数组
                byte[][] fileBytes = (byte[][]) paramMap.get("fileBytes");
                String[] fileBytesNames = (String[]) paramMap.get("fileBytesNames");//字节流文件名数组
                if (fileBytes != null) {
                    for (int i = 0; i < fileBytes.length; i++) {
                        builder.addFormDataPart(fileKey, fileBytesNames[i], RequestBody.create(MediaType.parse("application/octet-stream"),fileBytes[i]));
                    }
                }
                requestBody = builder.build();
                break;
            default:
                throw new RuntimeException("type参数错误");
        }

        request = new Request.Builder().post(requestBody).url(url);
        return this;
    }

    public OkHttpUtil put() {
        String json = "";
        if (paramMap != null) {
            json = JSON.toJSONString(paramMap);
        }
        RequestBody requestBody =  RequestBody.create( MediaType.parse("application/json; charset=utf-8"),json);
        request = new Request.Builder().put(requestBody).url(url);
        return this;
    }

    public OkHttpUtil del() {
        String json = "";
        if (paramMap != null) {
            json = JSON.toJSONString(paramMap);
        }

        RequestBody requestBody = RequestBody.create( MediaType.parse("application/json; charset=utf-8"),json);
        request = new Request.Builder().delete(requestBody).url(url);
        return this;
    }


    //下载文件,到指定路径  ,注意这种方式是异步的,不用等待下载完成就可以执行后面的代码
    public void downloadFileAsync(String filePath) {
        okHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure( Call call,  IOException e) {
                System.out.println("下载失败：" + e.getMessage());
            }

            @Override
            public void onResponse( Call call,  Response response) throws IOException {
                assert response.body() != null;
                FileOutputStream fileOutputStream = null;
                try (InputStream inputStream = response.body().byteStream()) {

                    File file = new File(filePath);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    fileOutputStream = new FileOutputStream(file);
                    IoStreamUtil.inputStreamToOutputStream(inputStream, fileOutputStream);
                } finally {
                    if (fileOutputStream != null) {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    }
                }
            }
        });
    }

    public void downloadFile(String filePath) {
        try {
            Response response = okHttpClient.newCall(request.build()).execute();
            assert response.body() != null;
            InputStream inputStream = response.body().byteStream();
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
            fileOutputStream.flush();
            fileOutputStream.close();
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //下载文件返回字节流
    public byte[] downloadFile() {

        try (Response response = okHttpClient.newCall(request.build()).execute()){

            assert response.body() != null;
            return response.body().bytes();
        } catch (IOException e) {
            throw new CommonException(e);
        }
    }

    //下载文件返回inputStream
    public InputStream downloadFileInputStream() {
        try (Response response = okHttpClient.newCall(request.build()).execute()) {
            assert response.body() != null;
            return response.body().byteStream();
        } catch (IOException e) {
            throw new CommonException(e);
        }
    }

    /**
     * 同步请求
     */
    public String sync() {
        setHeader(request);
        for (int i = 0; i < 3; i++) {
            try (Response response = okHttpClient.newCall(request.build()).execute()) {
                assert response.body() != null;
                return response.body().string();
            } catch (IOException e) {
                log.error("{}请求失败开始重试次数：{}", url, i, e);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    log.warn("同步请求线程中断", ex);
                    Thread.currentThread().interrupt();
                }
            }
        }
        throw new CommonException(url + "重试3次还是请求失败,请检查请求地址是否正确或者网络是否异常");

    }

    /**
     * 异步请求，有返回值
     */
    public void async(Consumer<String> consumer) {
        setHeader(request);
        AtomicInteger count = new AtomicInteger(3);
        okHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure( Call call,  IOException e) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e1) {
                    log.warn("异步请求线程中断", e1);
                    Thread.currentThread().interrupt();
                }
                if (count.decrementAndGet() == 0) {
                    log.error("{}请求失败", url, e);
                }
                log.error("请求失败开始重试,剩余次数：{}", count.get(), e);
                okHttpClient.newCall(request.build()).enqueue(this);
            }

            @Override
            public void onResponse( Call call,  Response response) throws IOException {
                if (response.body() == null) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        log.warn("异步请求线程中断", e);
                        Thread.currentThread().interrupt();
                    }
                    if (count.decrementAndGet() == 0) {
                        log.error("{}请求失败并且已经重试3次返回值还是为空", url);
                    }
                    log.error("请求结果是空开始重试,剩余次数：{}", count.get());
                    okHttpClient.newCall(request.build()).enqueue(this);
                }
                consumer.accept(response.body().string());
            }
        });


    }

    /**
     * 异步请求，带有接口回调
     */
    public void async(ICallBack callBack) {
        setHeader(request);
        okHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure( Call call,  IOException e) {
                callBack.onFailure(call, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                assert response.body() != null;
                callBack.onSuccessful(call, response.body().string());
            }
        });
    }

    /**
     * 为request添加请求头
     */
    private void setHeader(Request.Builder request) {
        if (headerMap != null) {
            try {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    request.addHeader(entry.getKey(), entry.getValue());
                }
            } catch (Exception e) {
                throw new CommonException(e);
            }
        }
    }


    /**
     * 生成安全套接字工厂，用于https请求的证书跳过
     */
    private static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustAllCerts) {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
            throw new CommonException(e);
        }
        return ssfFactory;
    }

    private static TrustManager[] buildTrustManagers() {
        return new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
    }

    /**
     * 自定义一个接口回调
     */
    public interface ICallBack {

        void onSuccessful(Call call, String data);

        void onFailure(Call call, String errorMsg);

    }
}

